package com.example.nyf.web.system;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.nyf.NyfApplication;
import com.example.nyf.common.AjaxResult;
import com.example.nyf.common.ConvertUtils;
import com.example.nyf.dto.SysMenuDTO;
import com.example.nyf.dto.SysRoleDTO;
import com.example.nyf.dto.SysUserTDO;
import com.example.nyf.entity.SysRole;
import com.example.nyf.entity.SysUser;
import com.example.nyf.service.SysRoleService;
import com.example.nyf.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController extends BaseController {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysRoleService sysRoleService;

    /**
     * 保存用户页面
     *
     * @param id 用户编号
     * @return
     */
    @RequestMapping("/system/add_user")
    public ModelAndView addUser(@RequestParam(value = "id", required = false, defaultValue = "") String id) {
        ModelAndView modelAndView = new ModelAndView("system/add_user.html");

        // 获取角色列表数据
        List<SysRole> sysRoleList = sysRoleService.getSysRoleList();
        String sysRoleListJson = JSON.toJSONString(sysRoleList);

        // 获取用户数据
        SysUserTDO sysUserTDO = sysUserService.getSysUserById(id);
        String sysUserJson = "{}";
        if (sysUserTDO != null) {
            sysUserTDO.setPassword("");
            sysUserJson = JSON.toJSONString(sysUserTDO);
        }

        modelAndView.addObject("sysRoleList", sysRoleListJson);
        modelAndView.addObject("sysUserJson", sysUserJson);

        return modelAndView;
    }

    /**
     * 保存用户
     * @param sysUserTDO
     * @param result
     * @return
     */
    @PostMapping("/system/save_add_user")
    @ResponseBody
    public AjaxResult saveAddUser(@RequestBody @Valid SysUserTDO sysUserTDO, BindingResult result) { //用对象接收json

        if (result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                throw new RuntimeException(error.getDefaultMessage());
            }
        }

        if("".equals(sysUserTDO.getId()) || sysUserTDO.getId()==null) {
            if(sysUserTDO.getPassword()==null || "".equals(sysUserTDO.getPassword())) {
                return AjaxResult.error("请输入密码");
            }
        }

        sysUserTDO.setAdd_user_id(getSysUser().getId());
        sysUserTDO.setAdd_user_name(getSysUser().getUser_name());
        sysUserTDO.setAdd_time((int)(System.currentTimeMillis()/1000));

        sysUserService.user_save(sysUserTDO);

        Logger logger = LoggerFactory.getLogger(UserController.class);
        logger.trace("slf4j 日志: 保存用户");

        return AjaxResult.success();
    }

    /**
     * 用户列表页面
     *
     * @return
     */
    @RequestMapping("/system/user_list")
    public ModelAndView sysUserList() {
        ModelAndView modelAndView = new ModelAndView("system/user_list.html");
        String listRole = "";
        List<SysRole> list = sysRoleService.getSysRoleList();
        if(list!=null) {
            listRole = JSON.toJSONString(list);
        }

        modelAndView.addObject("role_list", listRole);

        return modelAndView;
    }


    @RequestMapping("/system/get_user_list")
    @ResponseBody
    public Map getSysUserList(@RequestBody String post) {
        JSONObject jsonObject = JSON.parseObject(post);
        int page = Integer.parseInt(jsonObject.getString("page"));
        int pageSize = Integer.parseInt(jsonObject.getString("page_size"));
        String userName = jsonObject.getString("user_name");
        String status = jsonObject.getString("status");
        String roleId = jsonObject.getString("role_id");

        Map<String, Object> mp = new HashMap();
        mp.put("user_name", userName);
        mp.put("status", status);
        mp.put("roleId", roleId);
        return sysUserService.getSysUserList(page, pageSize, mp);
    }

    @GetMapping("/system/delete_user")
    @ResponseBody
    public AjaxResult deleteSysUser(@RequestParam("id") Integer user_id) {
        sysUserService.deleteSysUser(user_id);
        return AjaxResult.success();
    }

    @PostMapping("/system/upload_pic")
    @ResponseBody
    public AjaxResult uploadAvatar(@RequestParam(value = "file") MultipartFile file, HttpServletRequest req, SysUser sysUser) {
        if (file.isEmpty()) {
            return AjaxResult.error("图片不能为空");
        }

        String destFileName = "";
        String fileName = "";
        try {
            //
            fileName = System.currentTimeMillis() + file.getOriginalFilename();
            // resources路径
//            ApplicationHome applicationHome = new ApplicationHome(this.getClass());
//            String path = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "/src/main/resources/uploads" ;
//            destFileName = path + File.separator + fileName;
            destFileName = req.getServletContext().getRealPath("") + "/uploads" + File.separator + fileName;

            File destFile = new File(destFileName);
            destFile.getParentFile().mkdirs();
            file.transferTo(destFile);

        } catch (FileNotFoundException e) {
            return AjaxResult.error("上传失败," +e.getMessage());
        } catch (IOException e) {
            return AjaxResult.error("上传失败," +e.getMessage());
        }

        return AjaxResult.success("上传成功", fileName );
    }

}